using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MoEngine;
using Microsoft.Xna.Framework;
using System.Diagnostics;
using Microsoft.Xna.Framework.Graphics;

namespace MoWinLib
{
    public class EngineForm : Form
    {
        protected ServiceContainer m_Services;
        protected GraphicsDeviceService m_GraphicsDeviceService;
        protected Core m_CoreInst;

        protected Stopwatch m_Timer;
        protected GameTime m_GameTime;

        public EngineForm()
        {
            // Create service provider
            m_Services = new ServiceContainer();
            if (!DesignMode)
            {
                m_GraphicsDeviceService = GraphicsDeviceService.AddRef(
                    Handle, ClientSize.Width, ClientSize.Height);

                // Register the service, so components like ContentManager can find it.
                m_Services.AddService<IGraphicsDeviceService>(m_GraphicsDeviceService);

                // Create a core
                m_CoreInst = NewCore(m_Services);


                m_CoreInst.Initialize();

                // Start the animation timer.
                m_Timer = Stopwatch.StartNew();

                m_GameTime = new GameTime();
                Application.Idle += new EventHandler(OnApplicationIdle);
            }        
        }

        protected override void OnCreateControl()
        {

            base.OnCreateControl();
        }

        void OnApplicationIdle(object sender, EventArgs e)
        {
            // record time
            TimeSpan elapsedTime = m_Timer.Elapsed - m_GameTime.TotalGameTime;
            TimeSpan totalTime = m_Timer.Elapsed;
            m_GameTime = new GameTime(totalTime, elapsedTime, totalTime, elapsedTime);

            // update 
            m_CoreInst.Update(m_GameTime);

            // draw
            m_CoreInst.Draw(m_GameTime);
        }

        protected virtual Core NewCore(IServiceProvider services)
        {
            return new Core(services);
        }
    }
}